package com.jxs.easysecurity.resource.http;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.AntPathMatcher;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * URL类型的保护资源的数据源。
 * @see UriResource
 * @author jiangxingshang
 */
public class UriResourceDataSource {

    private AntPathMatcher matcher = new AntPathMatcher();
    private List<String> keys = new ArrayList<>();
    private Map<String, UriResource> resources = new HashMap<>();

    /**
     * 设置资源数据源。
     * @param resources
     */
    public void setResources(List<? extends UriResource> resources) {
        resources.forEach(this::addResource);
    }

    public UriResourceDataSource addResource(UriResource resource) {
        keys.add(resource.getId());
        resources.put(resource.getId(), resource);
        return this;
    }

    public List<String> getAllResourceId() {
        return keys.stream().collect(Collectors.toList());
    }

    public UriResource match(String uri, String method) {
        for(String key : keys) {
            if(matcher.match(resources.get(key).getUri(), uri)) {
                UriResource sr = resources.get(key);
                if(ArrayUtils.isEmpty(sr.getMethod()) || ArrayUtils.contains(sr.getMethod(), method)) {
                    return sr;
                }
            }
        }
        return null;
    }
}
